<!--新增或删除商品-->
<script setup>
import {useRouter} from "vue-router";
import {computed, onMounted, reactive, ref} from "vue";
import axios from "axios";
import {Delete, InfoFilled, View} from "@element-plus/icons-vue";
import qs from "qs";
import {ElMessage} from "element-plus";

const router=useRouter();
let foodList=ref([]);
let food=ref({})
let form=ref({})
let businessId=ref();
let businessName=ref();
let currentPage=ref(1);
let total=ref(0);
let pageSize=ref(5)
let dialogFormVisible1=ref(false)
let dialogFormVisible2=ref(false)
let formRef1=ref()
let formRef2=ref()

const validateNumber = (rule, value, callback) => {
  if (value === '' || isNaN(value) || Number(value) < 0) {
    callback(new Error('请输入一个大于或等于0的数字'));
  } else {
    callback();
  }
};

const rules = reactive({
  foodName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  foodExplain: [{ required: true, message: '请输入门店地址', trigger: 'blur' }],
  foodImg: [{ required: true, message: '请上传头像', trigger: 'blur' }],
  foodPrice: [
    { required: true, message: '请输入起送价', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],

});


onMounted( async () => {
  businessId.value = router.currentRoute.value.query.businessId
  businessName.value = router.currentRoute.value.query.businessName
  getFoodListById()
  // console.log(pagedShopList.value);
})

async function getFoodListById() {
  const response = await axios.get("/admin/getFoodListById",
      {
        params: {
          pageSize: pageSize.value,
          pageNum: currentPage.value,
          businessId:businessId.value
        }
      });
  console.log(response.data)
  foodList.value = response.data.list
  total.value = response.data.totalCount
}

function handleSizeChange(newSize){
  pageSize.value=newSize
  getFoodListById()
}
function handleCurrentChange(newPage){
  // console.log(newPage)
  currentPage.value=newPage
  getFoodListById()
}

function editFood(fd){
  food.value=fd;
  dialogFormVisible1.value=true

}
function addFood(){

  dialogFormVisible2.value=true

}

async function updateFood(fr) {
  console.log(food.value)

  if (!fr) return
  await fr.validate(async (valid) => {
    // console.log(valid,666)
    if (valid) {
      const response = await axios.post('/admin/updateFoodInfo', food.value);
      dialogFormVisible1.value = false;
      getFoodListById();
      food.value={}
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('请填写完整的表单信息');
    }
  });
}

const updateAvatar1 = (event) => {
  const file = event.target.files[0];
  if (file) {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
      ElMessage.error('上传的文件必须是图片!');
      return;
    }
    if (!isLt2M) {
      ElMessage.error('上传的图片大小不能超过 2MB!');
      return;
    }

    // avatar.value = file;
    // avatar.value = URL.createObjectURL(file);// 用于预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      // avatar.value = reader.result; // Base64 编码
      // console.log(avatar.value)
      food.value.foodImg = reader.result;
    };
    reader.onerror = () => {
      ElMessage.error('文件读取失败');
    };

  }
  // 清空文件输入元素的值，以便再次选择相同的文件时能够触发 change 事件
  event.target.value = '';
}
const updateAvatar2 = (event) => {
  const file = event.target.files[0];
  if (file) {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
      ElMessage.error('上传的文件必须是图片!');
      return;
    }
    if (!isLt2M) {
      ElMessage.error('上传的图片大小不能超过 2MB!');
      return;
    }

    // avatar.value = file;
    // avatar.value = URL.createObjectURL(file);// 用于预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      // avatar.value = reader.result; // Base64 编码
      // console.log(avatar.value)
      form.value.foodImg = reader.result;
    };
    reader.onerror = () => {
      ElMessage.error('文件读取失败');
    };

  }
  // 清空文件输入元素的值，以便再次选择相同的文件时能够触发 change 事件
  event.target.value = '';
}


async function createFood(fr) {
  form.value.businessId=businessId.value

  console.log(form.value)

  if (!fr) return
  await fr.validate( async (valid) => {
    // console.log(valid,666)
    if (valid) {
      const response = await axios.post('/admin/createFood', form.value);
      dialogFormVisible2.value = false;
      getFoodListById();
      form.value={}
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('请填写完整的表单信息');
    }
  });


}

function dialogFormClose2() {
  dialogFormVisible2.value = false;
  form.value = {}
}
async function deleteFood(foodId) {
  const requestData = {
    foodId: foodId,
  };
  // console.log(requestData)
  await axios.post("/admin/deleteFood",requestData).then(res=>{
    console.log(res)
    ElMessage.success("删除成功");
  }).catch(err=>{
    ElMessage.error("删除失败")
    console.log(err);
  })

  getFoodListById()

}


</script>

<template>
  <el-card style="background-color: #c0c0c0;">
    <div style="display: flex; align-items: center;">
      <div style="flex: 1; text-align: center;">{{ businessName }}</div>
      <div style="margin-left: auto;">
        <el-button @click="addFood">新增食品</el-button>
      </div>
    </div>
  </el-card>
<!--  <div style="margin: 10px 0; display: flex">-->

<!--    <el-button type="primary" @click="handleAdd" >新增 <i class="el-icon-circle-plus-outline"></i></el-button>-->
<!--  </div>-->
  <div>
    <el-table :data="foodList" stripe style="width: 100%">
      <el-table-column prop="foodId" label="ID" width="50"></el-table-column>
      <el-table-column label="商品图片">
        <template #default="scope">
          <el-image :src="scope.row.foodImg" fit="cover" style="width: 100px; height: 100px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="foodName" label="商品名称" ></el-table-column>
      <el-table-column prop="foodExplain" label="描述" ></el-table-column>
      <el-table-column prop="foodPrice" label="价格" ></el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button type="success" @click="editFood(scope.row)"><el-icon style="margin-right: 3px" ><View /></el-icon> 修改</el-button>
          <el-popconfirm
              width="220"
              confirm-button-text="OK"
              cancel-button-text="No, Thanks"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确认删除吗?"
              @confirm="deleteFood(scope.row.foodId)"
          >
            <template #reference>
              <el-button type="danger" ><el-icon style="margin-right: 3px"><Delete /></el-icon> 删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>

    <el-dialog v-model="dialogFormVisible1" title="修改食品">
      <el-form :model="food" :rules="rules" ref="formRef1">
        <el-form-item label="头像上传" prop="foodImg">
          <el-image :src="food.foodImg" class="image_1" style="border-radius: 3px 3px 0 0">
            <template #error>
              <div class="error">暂无头像</div>
            </template>
          </el-image>
          <el-button style="margin-left: 20px" @click="$refs.upload.click()">上传头像
            <input
                ref="upload"
                style="display: none"
                name="file"
                type="file"
                @change="updateAvatar1"
            />
          </el-button>
        </el-form-item>
        <el-form-item label="食品名称" :label-width="80" prop="foodName">
          <el-input v-model="food.foodName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="食品简介" :label-width="80" prop="foodExplain">
          <el-input v-model="food.foodExplain" autocomplete="off" />
        </el-form-item>

        <el-form-item label="食品价格" :label-width="80" prop="foodPrice">
          <el-input v-model="food.foodPrice" autocomplete="off"  />
        </el-form-item>

      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false;">Cancel</el-button>
        <el-button type="primary" @click="updateFood(formRef1)">
          Confirm
        </el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible2" title="新增食品">
      <el-form :model="form" :rules="rules" ref="formRef2">
        <el-form-item label="头像上传" prop="businessImg">
          <el-image :src="form.foodImg" class="image_1" style="border-radius: 3px 3px 0 0">
            <template #error>
              <div class="error">暂无头像</div>
            </template>
          </el-image>
          <el-button style="margin-left: 20px" @click="$refs.upload.click()">上传头像
            <input
                ref="upload"
                style="display: none"
                name="file"
                type="file"
                @change="updateAvatar2"
            />
          </el-button>
        </el-form-item>
        <el-form-item label="食品名称" :label-width="80" prop="foodName">
          <el-input v-model="form.foodName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="食品简介" :label-width="80" prop="foodExplain">
          <el-input v-model="form.foodExplain" autocomplete="off" />
        </el-form-item>

        <el-form-item label="食品价格" :label-width="80" prop="foodPrice">
          <el-input v-model="form.foodPrice" autocomplete="off"  />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormClose2">Cancel</el-button>
        <el-button type="primary" @click="createFood(formRef2)">
          Confirm
        </el-button>
      </span>
      </template>
    </el-dialog>
    <!--分页-->
    <div class="example-pagination-block">

      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"

          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>

</template>

<style scoped>
.example-pagination-block{
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
.image_1 {
  width: 275px;
  height: 260px;
  background: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.error {
  margin: 100px auto;
  width: 50%;
  padding: 10px;
  text-align: center;
}
</style>